package br.com.millenium.domain.manager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import lumis.portal.authentication.SessionConfig;
import lumis.portal.dao.jdbc.ITransactionJdbc;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.transaction.ITransaction;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.portal.user.UserConfig;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class BuscarFilialManager implements IBuscarFilialManager
{
	@SuppressWarnings("unchecked")
	@Override
	public JSONArray listaFilial(String bandeiraId, SessionConfig sessionConfig) 
	{
		JSONObject filiais = new JSONObject();
		JSONArray filiaisArray2 = new JSONArray();
		
		try
		{
			ITransaction transaction = PortalTransactionFactory.createTransaction();
			String       userId      = sessionConfig.getUserId();
			UserConfig   currentUser = ManagerFactory.getUserManager().get(sessionConfig, userId, transaction);
			
			transaction.begin();
			
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection       connection         = daoTransactionJdbc.getConnection();
			
			String query = "SELECT codigoFilial, id \n"+
						   "FROM MM_Filial \n"+
					       "WHERE bandeiraId = ?";
			
			PreparedStatement statement = connection.prepareStatement(query);
			
			statement.setString(1, bandeiraId);
			
			ResultSet rs = statement.executeQuery();
			int       n = 0;
			
			while(rs.next())
			{
				JSONArray filiaisArray = new JSONArray();
				
				filiaisArray.add(rs.getString("id")          );
				filiaisArray.add(rs.getString("codigoFilial"));
				
				filiais.put("filial"+n, filiaisArray.toJSONString());
				
				filiaisArray2.add(0, filiaisArray.toJSONString());
				n++;
			}
			
			filiais.put("size", filiais.size());
			
			rs.close();
			statement.close();
			connection.close();
			
			transaction.commit();
			transaction.dispose();
		}
		catch (Exception e)
		{
			e.getStackTrace();
		}
		
		return filiaisArray2;
	}
}
